<template>
    
    <div style="margin-top: 20px;">
        <!-- 屠宰信息 -->
        <div >
            <div>
                <h3 style="font-weight: bold;color:deepskyblue;float: left;margin-right: 20px">屠宰信息</h3>
                <el-button style="float:left;" @click="addInfo">设置</el-button>
            </div>
            <br><br><hr><br>
            <div style="float: left;width: 300px;">
                <h4>批次 : {{ pc }}</h4>
            </div>
            <div style="float: left;">
                <h4>到厂均重 : {{ data.siWeigth }}</h4>
            </div>
            <br><br>
            <div style="float: left;width: 300px;">
                <h4>到厂时间 : {{ data.siStaDate }}</h4>
            </div>
            <div style="float: left;">
                <h4>屠宰时间 : {{ data.siDate }}</h4>
            </div>
            <br><br>

        </div>
        
        <!-- 相关资质 -->
        <div :style="computedHeight">
            <div>
                <h3 style="font-weight: bold;color:deepskyblue;">相关资质</h3>
            </div>
            <br><hr><br>
            <div>
              <el-upload v-model:file-list="fileList" :action="lis" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-success="handleUploadSuccess"
                        :on-error="handleUploadError" :on-remove="handleRemove">
                        <el-icon><Plus /></el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisible" >
                        <img w-full  style="width: 80%; height: 80%;" :src="dialogImageUrl" alt="Preview Image"/>
                    </el-dialog>
            </div>
        </div>

        
        <!-- 企业信息 -->
        <div style="float:left;width: 100%;">
          <br>
            <div>
                <h3 style="font-weight: bold;color:deepskyblue;float: left;margin-right: 20px">企业信息</h3>
                <el-button style="float:left;" @click="addInfoyz">设置</el-button>
            </div>
            <br><br><hr><br>
            <div style="float: left;width: 300px;">
                <h4>公司名称 : {{ datayz.sqyName}}</h4>
            </div>
            <div style="float: left;">
                <h4>成立时间 : {{ datayz.sqyDate }}</h4>
            </div>
            <br><br>
            <div style="float: left;width: 300px;">
                <h4>公司地址 : {{ datayz.pname+' '+datayz.cname+' '+datayz.cxname }}</h4>
            </div>
            <br><br>
            <div style="float: left;width: 100%;">
                <h4>公司简介 : {{ datayz.sqyBrief }}</h4>
            </div>
            <br><br>

        </div>

        <!-- 企业图片 -->
        <div :style="computedHeightqy">
          <br>
            <div>
                <h3 style="font-weight: bold;color:deepskyblue;">企业图片</h3>
            </div>
            <br><hr><br>
            <div>
              <el-upload v-model:file-list="fileListqy" :action="lisqy" list-type="picture-card"
                        :on-preview="handlePictureCardPreviewqy" :on-success="handleUploadSuccessqy"
                        :on-error="handleUploadErrorqy" :on-remove="handleRemoveqy">
                        <el-icon><Plus /></el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisibleqy">
                        <img w-full style="width: 80%; height: 80%;" :src="dialogImageUrlqy" alt="Preview Image"/>
                    </el-dialog>
            </div>
        </div>

    </div>
    

    <!-- 设置屠宰信息 -->
  <el-dialog v-model="addshow" title="屠宰信息" style="max-width: 600px;height: 450px">
    <el-form ref="ruleFormRef" style="max-width: 100%;height: 100px" :model="input"
    :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize"
    status-icon >
    <el-form-item label="批次" prop="tmBatch">
      <el-input v-model="input.tmBatch" />
    </el-form-item>
    <el-form-item label="到厂均重" prop="siWeigth">
      <el-input v-model="input.siWeigth" />
    </el-form-item>
    <el-form-item label="到厂时间" prop="siStaDate">
        <el-col>
        <el-form-item prop="date1">
          <el-date-picker
            v-model="input.siStaDate"
            type="date"
            aria-label="Pick a date"
            placeholder="Pick a date"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-form-item>
    <el-form-item label="屠宰时间" prop="siDate">
        <el-col>
        <el-form-item prop="date1">
          <el-date-picker
            v-model="input.siDate"
            type="date"
            aria-label="Pick a date"
            placeholder="Pick a date"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-form-item>
    <br><hr><br>
    <el-form-item style="float:right;">
      <el-button type="primary" @click="adds(ruleFormRef)">
        保存
      </el-button>
    </el-form-item>
  </el-form>
  </el-dialog>



  
    <!-- 设置企业信息 -->
    <el-dialog v-model="addshowyz" title="养殖信息" style="max-width: 600px;height: 450px">
    <el-form ref="ruleFormRefyz" style="max-width: 100%;height: 100px" :model="inputyz"
    :rules="rulesyz" label-width="auto" class="demo-ruleForm" :size="formSizeyz"
    status-icon >
    <el-form-item label="公司名称" >
      <el-input v-model="inputyz.sqyName" prop='sqyName'/>
    </el-form-item>
    <el-form-item label="公司地址">
      <el-select style="width:150px" v-model="inputyz.pid" placeholder="省" @change="getc(),getcx()">
        <el-option v-for="item in province" :key="item.pid" :label="item.pName" :value="item.pid"  />
      </el-select>
      
      <el-select style="width:150px;margin-left: 20px" v-model="inputyz.cid" placeholder="市" @change="getcx()">
        <el-option v-for="item in city" :key="item.cid" :label="item.cName" :value="item.cid"   />
      </el-select>
      
      <el-select style="width:150px;margin-left: 20px" v-model="inputyz.cXid" placeholder="县">
        <el-option v-for="item in county" :key="item.cXid" :label="item.cxName" :value="item.cXid"/>
      </el-select>

    </el-form-item>
    <el-form-item label="成立时间">
        <el-col>
        <el-form-item prop="date1">
          <el-date-picker
          v-model="inputyz.sqyDate"
            type="date"
            aria-label="Pick a date"
            placeholder="Pick a date"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-form-item>
    <el-form-item label="公司简介" >
      <el-input v-model="inputyz.sqyBrief" type="textarea" />
    </el-form-item>
    <br><hr><br>
    <el-form-item style="float:right;">
      <el-button type="primary" @click="addsyz(ruleFormRef)">
        保存
      </el-button>
    </el-form-item>
  </el-form>
  </el-dialog>


</template>
<script lang="ts" setup>
import{ref,onMounted,reactive,inject,computed } from 'vue'
import { type AxiosStatic } from 'axios';
const axios=inject('axios') as AxiosStatic
import { ElMessage,ElMessageBox } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

onMounted(()=>{
    //console.log(localStorage.getItem('tmid'))
    Infoshows()//屠宰信息
    shows()//相关资质
    Infoshowsyz()//企业信息
    showsqy()//企业图片
})
// #region 屠宰信息
const data=ref({})
const pc=ref('')
//显示屠宰信息
const Infoshows=()=>{
    axios.get('/Slaughter/GetSlaughter?tmid='+localStorage.getItem('tmid'))
    .then((res)=>{
        //console.log(res.data,res.data.length,localStorage.getItem('pc'))
        if(res.data.length>0){
            res.data[0].siDate=res.data[0].siDate.substring(0,10)
            res.data[0].siStaDate=res.data[0].siStaDate.substring(0,10)
            data.value=res.data[0]
        }
            pc.value=localStorage.getItem('pc')
            //console.log(pc.value)
        
        //console.log(data.value)
    })
}

const input=reactive({
    tmBatch: "",
    siWeigth: "",
    siStaDate: "",
    siDate: "",
  tMid:localStorage.getItem('tmid')
})
//是否打开养殖信息
const addshow=ref(false)
//打开养殖信息弹框
const addInfo=()=>{
    //console.log(data.value.ciFeedPeople)
    addshow.value=true
    if(data.value.tmBatch!=null){
            input.tmBatch=data.value.tmBatch
            input.siWeigth=data.value.siWeigth
            input.siStaDate=data.value.siStaDate
            input.siDate=data.value.siDate
            input.tMid=data.value.tMid
        }else{
            input.tmBatch=pc.value
        }
}


const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//非空
const rules = reactive<FormRules<RuleForm>>({
    tmBatch: [
    { required: true, message: '批次不能为空', trigger: 'blur' },
  ],
  siWeigth: [
    { required: true, message: '到厂均重不能为空', trigger: 'blur' },
  ],
  siStaDate: [
    { required: true, message: '到厂时间不能为空', trigger: 'blur' },
  ],
  siDate: [
    { required: true, message: '屠宰时间不能为空', trigger: 'blur' },
  ],
})
const adds = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
            axios.post('/Slaughter/AddSlaughter',input)
            .then((res)=>{
                pc.value=input.tmBatch
                localStorage.removeItem('pc')
                localStorage.setItem('pc',input.tmBatch)
                //console.log(res.data)
                if(res.data>0){
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    addshow.value=false
                    Infoshows()
                    window.location.reload()
                }
            })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// #endregion

//#region 相关资质

const num=ref([])
//图片
const fileList = ref<UploadUserFile[]>([])
//显示
const shows=()=>{
    axios.get('/Slaughter/GetSlaughterImg?tmid='+localStorage.getItem('tmid'))
    .then((res)=>{
        //console.log(res.data)
        num.value=res.data.length
        if (Array.isArray(res.data)) {
        fileList.value = res.data.map((image) => ({
          name: image.sImgid || 'default-name.jpeg',  // 根据需要设置图片名称
          url: image.sImgurl
        }));
      } else {
        console.error('Unexpected response data format:', res.data);
      }
    })
}
const computedHeight=computed(()=> {
    shows()
    return {
        height: num.value < 7 ? '230px' : '390px', // 直接返回字符串
        alignItems: 'center',
        margin: '0 auto',
        float: 'left',
        width: '100%'
      };
    })

const lis = computed(() => {
  return fileList.value.length > 9 ? '' : 'http://182.92.209.50:8001/api/TraceManage/GetImage';
});
// 判断是否禁用上传按钮
//const isUploadDisabled = computed(() => fileList.value.length > 9);
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
//删除图片
const handleRemove: UploadProps['onRemove'] = (url) => {
  console.log(url.name)
    axios.post('/Slaughter/DelSlaughterImg?ids='+url.name)
    .then((res)=>{
        //console.log(res.data,num.value)
        if(num.value==7){
          shows()//相关资质
      }
    })
}
//预览图片处理事件
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
//上传成功后
const handleUploadSuccess=(url)=>{
  //console.log(url)
  axios.post('/Slaughter/AddSlaughterImg',{
    tMid:localStorage.getItem('tmid'),
    sImgurl:url,
    addName:"张三"
  })
  .then((res)=>{
    //console.log(res.data)
    if(num.value==6){
    shows()//动检证
    }
  })
}
//上传失败
const handleUploadError = (err) => {
    shows()
    if(num.value==9){
        ElMessage.error(`最多上传9张图片`);
    }else{
        ElMessage.error(`图片上传失败，请重试！`);
    }
};

//#endregion

// #region 企业信息


const inputyz=reactive({
  pid: "",//省
  cid: "",//市
  cXid: '',//县
  sqyName:'',//公司名称
  sqyDate:'',//成立时间
  sqyBrief:'',//简介
  tMid:localStorage.getItem('tmid')
})

//省
const province=ref([])
const getp=()=>{
  return axios.get('/Slaughter/GetProvince')
    .then((res)=>{
        //console.log(res.data)
        province.value=res.data
    })
}

//市
const city=ref([])
const getc=()=>{
    return axios.get('/Slaughter/GetCity?pid='+inputyz.pid)
    .then((res)=>{
        console.log(res.data)
        city.value=res.data
        inputyz.cid=''
    })
}

//县
const county=ref([])
const getcx=()=>{
  if(inputyz.cid==''){
    return
  }
  return axios.get('/Slaughter/GetCounty?cid='+inputyz.cid)
    .then((res)=>{
        console.log(res.data)
        county.value=res.data
        inputyz.cXid=''
    })
}

const datayz=ref({})
const address=ref('')
//显示企业信息
const Infoshowsyz=()=>{
    axios.get('/Slaughter/GetSlaughterQY?tmid='+localStorage.getItem('tmid'))
    .then((res)=>{
        console.log(res.data,res.data.length)
        if(res.data.length>0){
             res.data[0].sqyDate=res.data[0].sqyDate.substring(0,10)
            datayz.value=res.data[0]
        }
        //console.log(data.value)
    })
}


//是否打开企业信息
const addshowyz=ref(false)
//打开企业信息弹框
const addInfoyz=async()=>{
    //console.log(data.value.ciFeedPeople)
    await getp()//获取省
    // getc()//获取市
    // getcx()//获取县
    if(datayz.value.sqyName!=null){
            inputyz.sqyName=datayz.value.sqyName
            inputyz.sqyDate=datayz.value.sqyDate
            inputyz.sqyBrief=datayz.value.sqyBrief
            inputyz.pid=datayz.value.pid
            await getc()//获取市
            inputyz.cid=datayz.value.cid
            await getcx()//获取县
            inputyz.cXid=datayz.value.cXid
            inputyz.tMid=datayz.value.tMid
        }
    addshowyz.value=true
}


const formSizeyz = ref<ComponentSize>('default')
const ruleFormRefyz = ref<FormInstance>()
//非空
const rulesyz = reactive<FormRules<RuleForm>>({
  sqyName: [
    { required: true, message: '养殖场不能为空', trigger: 'blur' },
  ],
})
const addsyz = async (formEl: FormInstance | undefined) => {
  if(inputyz.sqyName==''){
    ElMessage({
            message: '公司名称不能为空',
            type: 'warning',
        })
        return 
  }
  if(inputyz.sqyDate==''){
    ElMessage({
            message: '成立时间不能为空',
            type: 'warning',
        })
        return
  }
  if(inputyz.sqyBrief==''){
    ElMessage({
            message: '简介不能为空',
            type: 'warning',
        })
  }
  if(inputyz.pid==''){
    ElMessage({
            message: '省不能为空',
            type: 'warning',
        })
  }
  if(inputyz.cid==''){
    ElMessage({
            message: '市不能为空',
            type: 'warning',
        })
  }
  if(inputyz.cXid==''){
    ElMessage({
            message: '县不能为空',
            type: 'warning',
        })
  }
            axios.post('/Slaughter/AddSlaughterQY',inputyz)
            .then((res)=>{
                //console.log(res.data)
                if(res.data>0){
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    addshowyz.value=false
                    Infoshowsyz()
                }
            })
}

// #endregion


//#region 企业图片

const numqy=ref([])
//图片
const fileListqy = ref<UploadUserFile[]>([])
//显示
const showsqy=()=>{
    axios.get('/Slaughter/GetSlaughterImg2?tmid='+localStorage.getItem('tmid'))
    .then((res)=>{
        //console.log(res.data)
        numqy.value=res.data.length
        if (Array.isArray(res.data)) {
        fileListqy.value = res.data.map((image) => ({
          name: image.sImgid || 'default-name.jpeg',  // 根据需要设置图片名称
          url: image.sImgurl
        }));
      } else {
        console.error('Unexpected response data format:', res.data);
      }
    })
}
const computedHeightqy=computed(()=> {
    showsqy()
    return {
        height: numqy.value < 7 ? '260px' : '410px', // 直接返回字符串
        alignItems: 'center',
        margin: '0 auto',
        float: 'left',
        width: '100%',
        // background: 'aqua'
      };
    })

const lisqy = computed(() => {
  return fileListqy.value.length > 9 ? '' : 'http://182.92.209.50:8001/api/TraceManage/GetImage';
});
// 判断是否禁用上传按钮
//const isUploadDisabled = computed(() => fileList.value.length > 9);
const dialogImageUrlqy = ref('')
const dialogVisibleqy = ref(false)
//删除图片
const handleRemoveqy: UploadProps['onRemove'] = (url) => {
  console.log(url.name)
    axios.post('/Slaughter/DelSlaughterImg2?ids='+url.name)
    .then((res)=>{
        //console.log(res.data,num.value)
        if(numqy.value==7){
          showsqy()//企业图片
      }
    })
}
//预览图片处理事件
const handlePictureCardPreviewqy: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrlqy.value = uploadFile.url!
  dialogVisibleqy.value = true
}
//上传成功后
const handleUploadSuccessqy=(url)=>{
  //console.log(url)
  axios.post('/Slaughter/AddSlaughterImg2',{
    tMid:localStorage.getItem('tmid'),
    sImgurl:url,
    addName:"张三"
  })
  .then((res)=>{
    //console.log(res.data)
    if(numqy.value==6){
          showsqy()//企业图片
    }
  })
}
//上传失败
const handleUploadErrorqy = (err) => {
    shows()
    if(numqy.value==9){
        ElMessage.error(`最多上传9张图片`);
    }else{
        ElMessage.error(`最多上传9张图片！`);
    }
};

//#endregion









</script>